//
//  DataAccess.m
//  RestkitDemo
//
//  Created by 刘硕 on 15/3/26.
//  Copyright (c) 2015年 Liu Shuo. All rights reserved.
//

#import "DataAccess.h"
#import <RestKit.h>
#import "Result.h"

#define kBaseUrl @"http://api.app.yiche.com"
#define kHttpsBaseUrl @"https://api.app.yiche.com"

@implementation DataAccess

+ (void)configHttp {
    [DataAccess clear];
    [DataAccess configSecure:NO];
}

+ (void)clear {
    if ([RKObjectManager sharedManager]) {
        [RKObjectManager setSharedManager:nil];
    }
}

+ (void)configSecure:(BOOL)secure {

#ifndef PA_RELEASE
    RKLogConfigureByName("RestKit/Network*", RKLogLevelTrace);
    RKLogConfigureByName("RestKit/ObjectMapping", RKLogLevelTrace);
#endif

    // let AFNetworking manage the activity indicator
    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;

    NSURL *baseURL = nil;
    if (secure) {
        baseURL = [NSURL URLWithString:kHttpsBaseUrl];
    } else {
        baseURL = [NSURL URLWithString:kBaseUrl];
    }

    RKObjectManager *manager = [RKObjectManager managerWithBaseURL:baseURL];
    [RKMIMETypeSerialization registerClass:[RKNSJSONSerialization class] forMIMEType:@"text/plain"];
    [manager.HTTPClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
    [manager setAcceptHeaderWithMIMEType:RKMIMETypeJSON];
    manager.requestSerializationMIMEType = RKMIMETypeJSON;
    [RKObjectManager setSharedManager:manager];

    RKObjectMapping *resultMapping = [RKObjectMapping mappingForClass:[Result class]];
    [resultMapping addAttributeMappingsFromArray:@[ @"ID", @"Status", @"Message", @"Data" ]];
    RKResponseDescriptor *responseDescriptor =
        [RKResponseDescriptor responseDescriptorWithMapping:resultMapping
                                                     method:RKRequestMethodAny
                                                pathPattern:nil
                                                    keyPath:nil
                                                statusCodes:[NSIndexSet indexSetWithIndex:200]];
    [manager addResponseDescriptor:responseDescriptor];
}

@end
